<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>
<script setup lang="ts">
import { onMounted, onUpdated, reactive, ref, Ref } from "vue";
import { IAnChartField } from "@/api/sys/model/entitysModel";
import { useECharts } from "@/hooks/web/useECharts";

const chartRef = ref<HTMLDivElement>();
const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
const height = ref("300px");
const width = ref("100%");
const props = defineProps({
  valueFetch: {
    type: Function,
    default: () => {
      return "";
    }
  },
  anChartField: {
    type: Object
  }
});

const actualAnChartField: IAnChartField = props.anChartField as IAnChartField;
const value = ref([{ value: 1048, name: "Search Engine" },
  { value: 735, name: "Direct" },
  { value: 580, name: "Email" },
  { value: 484, name: "Union Ads" },
  { value: 300, name: "Video Ads" }]);
const option = reactive({
  tooltip: {
    trigger: "item"
  },
  legend: {
    top: 0,
    left: "center"
  },
  series: [
    {
      name: actualAnChartField.name,
      type: "pie",
      data: value,
      radius: "60%",
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: false
        }
      },
      labelLine: {
        show: false
      }
    }
  ]
});

function init() {
  props.valueFetch().then(
    res => {
      value.value = res.value
        .map((item: any) => {
          return {
            value: item.itemCount || item.ITEMCOUNT || item.itemcount,
            name: item.item || item.ITEM
          };
        });
      setOptions(option);
      console.log(option);
      console.log(value.value);
    }
  );
}

onUpdated(
  () => {
    init();
  }
);
onMounted(() => {
  init();
});
</script>
